package devcontainer

import (
	Result "code.gitea.io/gitea/routers/entity"
	gitea_web_context "code.gitea.io/gitea/services/context"
	devcontainer_api_service "code.gitea.io/gitea/services/devstar_devcontainer/api_services"
	"code.gitea.io/gitea/services/devstar_devcontainer/options"
	"strconv"
)

// GetDevcontainer 查找某用户在某仓库的 DevContainer
//
// GET /api/devcontainer
// 请求体参数：
// -- repoId: 需要为哪个仓库创建 DevContainer
// -- wait: 是否等待 DevContainer 就绪（默认为 false 直接返回“未就绪”，否则阻塞等待）
// 注意：必须携带 用户登录凭证
func GetDevcontainer(ctx *gitea_web_context.Context) {
	// 1. 检查用户登录状态，若未登录则返回未授权错误
	if ctx == nil || ctx.Doer == nil {
		Result.RespUnauthorizedFailure.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 2. 取得参数
	wait := ctx.FormBool("wait")
	repoIdStr := ctx.FormString("repoId")
	repoId, err := strconv.ParseInt(repoIdStr, 10, 64)
	if err != nil || repoId <= 0 {
		Result.RespFailedIllegalParams.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 3. 准备调用 API Service 层，获取 DevContainer 信息
	optsAbstractOpenDevcontainer := &options.AbstractOpenDevcontainerOptions{
		Wait:   wait,
		RepoId: repoId,
		Actor:  ctx.Doer,
	}
	repoDevcontainerVO, err := devcontainer_api_service.OpenDevcontainerAPIService(ctx, optsAbstractOpenDevcontainer)
	if err != nil {
		failureGetDevcontainer := Result.ResultType{
			Code: Result.RespFailedOpenDevcontainer.Code,
			Msg:  Result.RespFailedOpenDevcontainer.Msg,
			Data: map[string]any{
				"ErrorMsg": err.Error(),
			},
		}
		failureGetDevcontainer.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 4. 封装返回成功信息
	successGetDevContainer := Result.ResultType{
		Code: Result.RespSuccess.Code,
		Msg:  Result.RespSuccess.Msg,
		Data: repoDevcontainerVO,
	}
	successGetDevContainer.RespondJson2HttpResponseWriter(ctx.Resp)
}
